<template>
    <div 
      class="scale-container" 
      :style="containerStyle"
      ref="containerRef"
    >
      <slot />
    </div>
  </template>
  
  <script setup>
  import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
  
  const props = defineProps({
    // 设计稿宽度（默认1920）
    designWidth: {
      type: Number,
      default: 1920
    },
    // 设计稿高度（默认1080）
    designHeight: {
      type: Number,
      default: 1080
    },
    // 最小缩放比例（默认0.5）
    minScale: {
      type: Number,
      default: 0.5
    },
    // 最大缩放比例（默认1.2）
    maxScale: {
      type: Number,
      default: 1.2
    },
    // 是否启用缩放（默认true）
    enabled: {
      type: Boolean,
      default: true
    }
  })
  
  const containerRef = ref(null)
  const scale = ref(1)
  
  const containerStyle = computed(() => ({
    transform: props.enabled ? `scale(${scale.value})` : 'none',
    width: `${props.designWidth}px`,
    height: `${props.designHeight}px`,
    transformOrigin: 'left top',
    position: 'relative'
  }))
  
  const updateScale = () => {
    if (!props.enabled) return
    
    const { clientWidth: width, clientHeight: height } = document.documentElement
    const scaleX = width / props.designWidth
    const scaleY = height / props.designHeight
    let newScale = Math.min(scaleX, scaleY)
    
    // 限制缩放范围
    newScale = Math.max(props.minScale, Math.min(newScale, props.maxScale))
    
    scale.value = newScale
    
    // 居中定位（可选）
    if (containerRef.value) {
      const offsetX = (width - props.designWidth * newScale) / 2
      const offsetY = (height - props.designHeight * newScale) / 2
      containerRef.value.style.left = `${offsetX}px`
      containerRef.value.style.top = `${offsetY}px`
    }
  }
  
  // 防抖处理
  let resizeTimer = null
  const handleResize = () => {
    clearTimeout(resizeTimer)
    resizeTimer = setTimeout(() => {
      updateScale()
    }, 100)
  }
  
  onMounted(() => {
    updateScale()
    window.addEventListener('resize', handleResize)
  })
  
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
  })
  
  // 暴露方法给父组件
  defineExpose({
    updateScale,
    getCurrentScale: () => scale.value
  })
  </script>
  
  <style scoped>
  .scale-container {
    overflow: hidden;
    transition: transform 0.3s ease;
  }
  </style>